import { relative } from "path";
import { useEffect, useRef, useState } from "react";
import { useHistory, useLocation } from "react-router-dom";
import BaseNode from "./container/BaseNode";
import { JoinLineType, NodeProp } from "./container/ContainerProvider";
import JoinLine from "./container/JoinLine";

export default function Preview() {
  const location = useLocation<{ nodes: NodeProp[]; lines: JoinLineType[] }>();
  const [width, setWidth] = useState(1000);
  const [height, setHeight] = useState(800);
  const divRef = useRef<HTMLDivElement>(null);
  const { nodes, lines } = location.state;
  const history = useHistory();
  useEffect(() => {
    if (divRef.current !== null) {
      setWidth(divRef.current.offsetWidth);
      setHeight(divRef.current.offsetHeight);
    }
  }, [divRef]);
  return (
    <div
      style={{ position: "relative", height: "90vh", width: "100%" }}
      ref={divRef}
    >
      <button
        style={{ position: "absolute", left: "30px" }}
        onClick={() => history.goBack()}
      >
        返回
      </button>
      <svg width={width} height={height}>
        {nodes &&
          nodes.map((node, index) => {
            return (
              <BaseNode
                {...node}
                key={index}
                index={index}
                fill={node.fill ? node.fill : "#ffffff"}
                stroke={"#333"}
              />
            );
          })}
        {lines &&
          lines.map((line, index) => {
            return <JoinLine {...line} key={index} />;
          })}
      </svg>
    </div>
  );
}
